package cn.hiapi.shopkeeper.service.activity;

import cn.hiapi.basic.ResUtils;
import cn.hiapi.basic.entity.BasicEntity;
import cn.hiapi.basic.exception.BasicException;
import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.redis.service.RedisService;
import cn.hiapi.basic.token.Token;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.shop.service.product.ProductNumService;
import cn.hiapi.shopkeeper.consts.AppConst;
import cn.hiapi.shopkeeper.entity.activity.Activity;
import cn.hiapi.shopkeeper.entity.activity.ActivityBargain;
import cn.hiapi.shopkeeper.entity.order.ActivityBargainOrder;
import cn.hiapi.shopkeeper.entity.order.ActivityOrder;
import cn.hiapi.shopkeeper.enums.ActivityType;
import cn.hiapi.shopkeeper.jpa.activity.ActivityBargainJpa;
import cn.hiapi.shopkeeper.request.CreateOrderRequest;
import cn.hiapi.shopkeeper.service.order.ActivityBargainOrderService;
import cn.hiapi.shopkeeper.service.order.ActivityBargainRecordService;
import cn.hiapi.shopkeeper.service.order.ActivityOrderService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

/**
 * @author AdinZ
 * @date 2022/12/13 0:34
 * 砍价活动
 */
@Service
public class ActivityBargainService extends AbsActivityService<ActivityBargainJpa, ActivityBargain, Long> {
    public ActivityBargainService(DispatchContext dispatchContext) {
        super(dispatchContext);
    }

    @Override
    public ActivityType getActivityType() {
        return ActivityType.BARGAIN;
    }

    @Override
    @Transactional
    public BasicEntity saveExpand(long activityId, JSONObject data) {
        ActivityBargain bargain = data.toJavaObject(ActivityBargain.class);
        if (StringUtils.isEmpty(bargain.getTitle()))
            throw new BasicException("商品标题错误");
        if (bargain.getMinPrice() == null || bargain.getMinPrice().compareTo(BigDecimal.ZERO) <= 0)
            throw new BasicException("最低价格错误");
        if (bargain.getStockNum() <= 0) throw new BasicException("商品数量错误");
        if (bargain.getCutCount() <= 0) throw new BasicException("砍价次数错误");
        bargain.setAid(activityId);
        return this.save(bargain);
    }

    @Override
    @Transactional
    public int deleteByAid(long aid) {
        return ResUtils.getDefault(this.repository.deleteByAid(aid));
    }

    @Override
    @Transactional
    public ActivityOrder createOrder(BasicEntity basic, Activity activity, Map<String, Long> incrementStock, CreateOrderRequest request, Token<Object> token) {
        ActivityBargain bargain = (ActivityBargain) basic;


        if (bargain.getLimitNum() != null && bargain.getLimitNum() > 0) {
            long count = this.dispatchContext.getServiceOne(ActivityOrderService.class).count(
                    new QueryWrapper().eq("aid", activity.getId())
                            .eq("buyerId",token.getFid())
                            .eq("statusType", 1).eq("activityType", activity.getType())
            );
            if (count >= bargain.getLimitNum())
                throw new BasicException("超过限购数量");
        }


        final int stockNum = bargain.getStockNum();
        long total = this.dispatchContext.getServiceOne(ProductNumService.class).totalByGid(activity.getId(), AppConst.ACTIVITY_SELL_TOTAL);
        long increment = this.dispatchContext.getServiceOne(RedisService.class).increment(AppConst.ACTIVITY_SELL_STOCK_KEY, activity.getId(), 0L);
        if ((total + increment) >= stockNum) {
            throw new BasicException("库存不足");
        }

        ActivityOrder order = new ActivityOrder();
        ActivityBargainOrder bargainOrder = this.dispatchContext.getServiceOne(ActivityBargainOrderService.class).get(activity.getId(), token.getFid());
        order.setPrice(activity.getPrice());
        order.setCostPrice(activity.getPrice());
        if (bargainOrder != null) {
            ActivityBargainRecordService.Total total1 = this.dispatchContext.getServiceOne(ActivityBargainRecordService.class).total(bargainOrder.getId());
            order.setFid(bargainOrder.getId());
            order.setFidType(AppConst.ACTIVITY_BARGAIN);
            order.setDiscount(total1.getTotalPrice());
            bargainOrder.setCount(total1.getCount());
            bargainOrder.setTotalPrice(total1.getTotalPrice());
        }
        return order;
    }

    @Override
    public BigDecimal sugarDeduction(Activity activity, BigDecimal rate, BigDecimal amount,long uid) {
        ActivityBargainOrder bargainOrder = this.dispatchContext.getServiceOne(ActivityBargainOrderService.class).get(activity.getId(), uid);
        if (bargainOrder != null) {
            ActivityBargainRecordService.Total total1 = this.dispatchContext.getServiceOne(ActivityBargainRecordService.class).total(bargainOrder.getId());
            return super.sugarDeduction(activity.getPrice().subtract(total1.getTotalPrice()),rate,amount);
        }
        return super.sugarDeduction(activity.getPrice(),rate,amount);
    }
}
